<template>
    <div>
    <el-button type="primary" v-if="addButtons" @click="addPermission(permission)">添加菜单</el-button>
        <el-table border :data="permissionList" :expand-row-keys="expandKeys" row-key="id" v-loading="dataLoading"
            style="margin-top: 20px;margin-bottom: 20px;">
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="codes" label="前端路由标识" />

            <el-table-column prop="urls" label="后端路径" />
      <el-table-column prop="method_types" label="请求方式" />
      <el-table-column label="类型">
        <template slot-scope="{row}">
          <span v-for="(item, index) in typeList" :key="index" v-if="item[0] == row.type">
             {{item[1]}}
          </span>

        </template>
      </el-table-column>
      <el-table-column label="是否启用">
        <template slot-scope="{row}">
          <span v-if="row.is_active">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>

            <el-table-column label="操作">
                <template slot-scope="{row}">

                    <HintButton type="primary" v-if="addButtons" icon="el-icon-plus" size="mini" :title="row.level<2 ? '添加菜单' : '添加功能'"
                        :disabled="row.level===3" @click="addPermission(row)" />

                    <HintButton type="primary" v-if="editButtons" icon="el-icon-edit" size="mini" :title="row.level===3 ? '修改功能' : '修改菜单'"
                         @click="updatePermission(row)" />

                    <HintButton type="danger" v-if="delButtons" icon="el-icon-delete" size="mini" title="删除" @click="deletePermission(row)" />
                </template>
            </el-table-column>
        </el-table>

        <el-dialog :visible.sync="dialogPermissionVisible" :title="dialogTitle" :before-close="resetData">

            <el-form ref="permission" :model="permission" :rules="permissionRules" label-width="120px">
                <el-form-item label="父级名称">
                    <el-input :value="permission.pname" disabled />
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="permission.name" />
                </el-form-item>

                <el-form-item label="后端路径" prop="urls">
                    <el-input v-model="permission.urls" />
                </el-form-item>

                <el-form-item label="前端路由标识" prop="codes">
                    <el-input v-model="permission.codes" />
                </el-form-item>

        <el-form-item label="请求方式" prop="method_types">

            <el-select v-model="permission.method_types" placeholder="请选择">
              <el-option v-for="item in methodList" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>

        </el-form-item>

        <el-form-item label="类型" prop="codes">
          <el-radio-group v-model="permission.type">
            <el-radio v-for="(item, index) in typeList" :key="item[1]" :label="item[0]" :disabled="radioType" >{{item[1]}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否启用" prop="is_active">

            <el-switch v-model="permission.is_active"></el-switch>
        </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetData">取 消</el-button>
                <el-button type="primary" @click="submitPermission">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

    // 菜单权限校验的规则
    const menuRules = {
      name: [{required: true, message: '名称必须输入'}],
      codes: [{required: true, message: '前端路由标识必须输入'}],
    }

    // 按钮功能权限校验的规则
    const btnRules = {
      name: [{required: true, message: '名称必须输入'}],
      codes: [{required: true, trigger: 'blur', message: '按钮的前端路由标识必须输入'}]
    }
    export default {
        name: 'PermissionList',

        data() {
            return {
                permissionList: [],
                typeList:[],
                methodList:[],
                expandKeys: [], // 需要自动展开的项
                dialogPermissionVisible: false, // 是否显示菜单权限的Dialog
                dataLoading: true, // 数据加载的loading
                radioType:false,
                permission: { // 要操作的菜单权限对象
                    level: 0,
                    name: '',
                    codes: '',
                    urls: '',
                    method_types: '',
                    is_active: true,
                    type: 10,
                    
                },
                
            }
        },

        computed: {
            /*
                动态计算得到Dialog的标题
            */
            dialogTitle() {
                const {id,level,type} = this.permission
                if (id) {
                    return level === 3 ? '修改功能' : '修改菜单'
                } else {
                    return type != 10 ? '添加功能' : `添加${level}级菜单`
                }
            },
            /*
                根据权限的等级来计算确定校验规则
            */
            permissionRules () {
                return this.permission.level===3 ? btnRules : menuRules
            },
            /*
                按钮的权限校验
            */
            addButtons(){
                return this.$util.isButton('system.permission.add')
            },
            editButtons(){
                return this.$util.isButton('system.permission.edit')
            },
            delButtons(){
                return this.$util.isButton('system.permission.delete')
            }

        },

        mounted() {
            this.getData()
        },

        methods: {
            async getData() {
                this.dataLoading = true;
                let result = await this.$API.permission.reqPermissionList();
                if (result.code == 200) {
                    this.permissionList = result.data.items;
                    this.typeList = result.data.type_list;
                    this.methodList = result.data.method_list;
                    // this.expandKeys = [this.permissionList[0].id]
                    this.dataLoading = false;
                }

            },
            authButton(key) {
                return this.$util.isButton(key)
            },
            // 显示添加
            addPermission(row) {
                this.dialogPermissionVisible = true;
                this.permission.parent = row.id ? row.id : null;
                this.permission.level = row ? row.level + 1 : 1;
                this.permission.pname = row.name ? row.name : '';   // 用于显示父名称, 但提交请求时是不需要的
                // this.$set(this.permission, 'pname', row.name)
        if(this.permission.level == 3){
          this.permission.type = 20;
          this.radioType = true;

        }
                this.$nextTick(()=>this.$refs.permission.clearValidate())

            },
            // 显示修改
            updatePermission(row){
                this.dialogPermissionVisible = true;
                this.permission = {...row}  // 使用深拷贝
        if(this.permission.level == 3){
          this.radioType = true;
        }
                this.$nextTick(()=>this.$refs.permission.clearValidate())
            },
            // 关闭窗口
            resetData() {
                this.dialogPermissionVisible = false;
                this.radioType = false;
                this.permission = {
                    level: 0,
                    name: '',
                    codes: '',
                    urls: '',
                    method_types: '',
                    is_active: true,
                    type: 10,
                }
            },
            // 提交新增或修改的数据
            submitPermission() {
                this.$refs.permission.validate(async (valid) => {
                    if (valid) {
                        const {pname,...permission} = this.permission
                        permission.method_types = permission.method_types == '无' ? '':permission.method_types;
                        let result = await this.$API.permission.reqAddOrUpdatePermission(permission)

                        if (result.code == 201 || result.code == 200) {
                            this.$message({
                                type: 'success',
                                message: result.code == 200 ? "修改成功" : "添加成功"
                            })
                            this.resetData()
                            this.getData()
                        }
                    } else {
                        this.$message({type:'error',message:this.permission.id ? "修改失败" : "添加失败"})
                        return false;
                    }
                });

            },
            // 删除菜单
            deletePermission(row) {
                this.$confirm(`此操作将永久删除${row.name}该数据, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let result = await this.$API.permission.reqRemovePermission(row.id)
                    if (result.status == 204) {
                        this.$message({
                            type: 'success',
                            message: `删除${row.name}成功！`
                        })
                        this.getData()
                    }

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: `已取消删除${row.name}！`
                    });
                });
            }
        }
    }
</script>
